<template>
    <div>
        <el-card v-loading="loading.data">
            <div slot="header">
                <el-button type="text" @click="$router.push('/project/'+project.id)">{{project.name}}</el-button>
                <el-button type="text" @click="$router.push('/project/'+project.id+'/report/'+urlDay)">{{day}} 日志
                </el-button>
                发送邮件
            </div>
            <el-form label-width="100px">
                <el-form-item label="收件邮箱">
                    <el-button @click="addTempEmail" type="text">临时添加收件人邮箱</el-button>
                    <br/>
                    <el-table border
                              :data="list"
                              ref="emailsTable"
                              @selection-change="selectionChange" height="300">
                        <el-table-column type="selection"/>
                        <el-table-column label="邮箱" prop="email"/>
                        <el-table-column label="用户名" prop="username"/>
                        <el-table-column label="身份" prop="role"/>
                    </el-table>
                </el-form-item>
                <el-form-item label="追加内容">
                    <report_email_append_link @add="appendLink"/>
                    <el-input type="textarea"
                              placeholder="在邮件内容尾部追加内容"
                              :autosize="{ minRows: 4, maxRows: 8}"
                              v-model="form.appendContent"/>
                </el-form-item>
                <el-form-item label="上传附件">
                    <upload_file_table
                            placeholder="点击文件名插入到追加内容中。"
                            :url="'/api/report/' + report.id + '/upload_file'"
                            @click="appendFile"
                            :defaultFiles="files"/>
                </el-form-item>
                <el-form-item>
                    <el-button @click="submitPreview" :loading="loading.data" type="primary">预览</el-button>
                    <el-button @click="send"
                               :disabled="form.emails.length ===0 || !status.preview"
                               :loading="loading.submitting"
                               type="success">发送
                    </el-button>
                    <el-alert title="预览确认无误后才能点击发送" type="warning" v-if="!status.preview"/>
                    <el-alert title="请选择邮箱" type="error" v-if="form.emails.length === 0"/>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card v-loading="loading.preview" v-show="status.preview">
            <div slot="header">预览 {{project.name}} {{day}} 日志邮件</div>
            <div ref="preview"></div>
        </el-card>
    </div>
</template>

<script>
    import moment from 'moment';
    import _ from 'lodash';
    import Report_email_append_link from "../component/report_email_append_link";
    import Upload_file_table from "../component/upload_file_table";

    export default {
        components: {Upload_file_table, Report_email_append_link},
        name: "report_send_mail",
        data() {
            return {
                project: {},
                report: {},
                dialogVisible: false,
                list: [],
                form: {emails: [], appendContent: ''},
                files: [],
                preview: false,
                change: false,
                loading: {data: true, preview: true, submitting: false,},
                status: {
                    preview: false,
                },
            }
        },
        computed: {
            day() {
                return moment(this.report.created_at).format('YYYY年MM月DD日');
            },
            urlDay() {
                return moment(this.report.created_at).format('YYYY-MM-DD');
            },
        },
        methods: {
            fetch() {
                let project_id = this.$route.params.id, report_date = this.$route.params.date;
                Promise.all([
                    this.$http.get(`/api/project/${project_id}/report/` + report_date),
                    this.$http.get(`/api/project/${project_id}/email`),
                ]).then(res => {
                    this.project = res[0].data.project;
                    this.report = res[0].data.report;
                    this.list = res[1].data;
                    this.loading.data = false;
                    this.$nextTick(() => {
                        this.list.forEach(mail => {
                            this.$refs['emailsTable'].toggleRowSelection(mail);
                        });
                    });
                    this.$http.get('/api/report/' + res[0].data.report.id + '/files').then(({data}) => {
                        this.files = data;
                    });
                });
            },
            selectionChange(rows) {
                this.form.emails = rows.map(item => item.email);
            },
            send() {
                this.loading.submitting = true;
                this.$http.post(`/api/report/${this.report.id}/send_email`, this.form).then(res => {
                    this.loading.submitting = false;
                    this.$alert(res.data, {type: 'success', dangerouslyUseHTMLString: true});
                }).catch(err => {
                    this.loading.submitting = false;
                    this.$alert(err.response.data, {type: 'error', dangerouslyUseHTMLString: true});
                });
            },
            addTempEmail() {
                this.$prompt('请输入邮箱', '提示', {
                    confirmButtonText: '追加',
                    inputPattern: /^[a-z0-9._\-]+@[a-z0-9]{2,}\.[a-z]{2,4}$/i,
                    inputErrorMessage: '邮箱格式不正确'
                }).then(({value}) => {
                    let find = _.find(this.list, {email: value});
                    if (find)
                        return this.$message.success(value + ' 已经存在');

                    this.list.push({email: value, username: '临时追加', role: '临时追加'});
                    this.$refs['emailsTable'].toggleRowSelection(this.list[this.list.length - 1]);
                }).catch(() => {
                });
            },
            submitPreview() {
                this.loading.preview = true;
                this.$http.post('/api/report/' + this.report.id + '/preview', this.form).then(({data}) => {
                    this.loading.preview = false;
                    this.status.preview = true;
                    this.$refs['preview'].innerHTML = data.html;
                });
            },
            appendFile(file) {
                let url = `https://live.beijingzhuyou.com/file/${file.file}`;
                let content;
                if (file.name.match(/jpg|jpeg|png|gif$/)) {
                    content = `<a href="${url}" title="${file.name}" target="_blank"><img src="${url}" alt="${file.name}"></a>`;
                } else {
                    content = `<a href="${url}" target="_blank">附件：${file.name}</a>`
                }
                console.log('appendFIle', content);
                this.form.appendContent += content;
            },
            appendLink(link) {
                let href = link.href.toLowerCase();
                if (href.indexOf('http://') === -1 && href.indexOf('https://') === -1)
                    href = 'http://' + href;
                this.form.appendContent += `<a href="${href}" target="_blank">${link.name}</a>`;
            }
        },
        mounted() {
            this.fetch();
        },
    }
</script>

<style scoped>
</style>